package com.liuyjy.thread.config;

import com.liuyjy.thread.properties.ThreadPoolProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author liuyjy
 * @Date 2025/2/27 15:21
 * @Description: 线程池配置
 **/
@EnableAsync
@Configuration
public class ThreadConfig {
    @Bean
    public ThreadPoolProperties threadPoolProperties(){
        return new ThreadPoolProperties();
    }

    /**
     * 綫程池配置
     */
    @Primary
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        ThreadPoolProperties properties = threadPoolProperties();
        // 设置核心线程数
        //Runtime.getRuntime().availableProcessors()+1;
        executor.setCorePoolSize(properties.getCorePoolSize());
        // 设置最大线程数
        //Runtime.getRuntime().availableProcessors()*2+1;
        executor.setMaxPoolSize(properties.getMaxPoolSize());
        // 设置队列容量
        executor.setQueueCapacity(properties.getQueueCapacity());
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(properties.getKeepAliveSeconds());
        // 设置默认线程名称
        executor.setThreadNamePrefix(properties.getThreadNamePrefix());
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}
